package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShopCartMapper shopCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
//    @Autowired
//    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //判断地址簿是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断配送距离是否超出了5公里
        String userAddress=null;
        userAddress=addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail();
        isAbleDelivery(userAddress);
        //判断购物车是否为空
        List<ShoppingCart> shoppingCartList= shopCartMapper.getByUserId(BaseContext.getCurrentId());
        if(shoppingCartList == null|| shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setAddressBookId(addressBook.getId());
        orders.setAddress(addressBook.getDetail());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPhone(addressBook.getPhone());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setConsignee(addressBook.getConsignee());
        //设置支付状态
        orders.setPayStatus(0);
        //设置订单状态
        orders.setStatus(1);
        //设置订单好，用时间戳
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //在订单表中拆一条数据
        orderMapper.add(orders);
        //在订单详情表中插入菜品数据
        List<OrderDetail> orderDetailList=new ArrayList<>();

        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        //批量插入
        orderDetailMapper.addBatch(orderDetailList);
        //清除购物车
        shopCartMapper.clean(BaseContext.getCurrentId());
        //封装响应对象
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        Orders orders = new Orders();
        Long id= orderMapper.getNumberById(ordersPaymentDTO.getOrderNumber());
        orders.setId(id);
        orders.setNumber(ordersPaymentDTO.getOrderNumber());
        orders.setPayStatus(1);
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orderMapper.update(orders);
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     *
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket向用户推送消息
        HashMap<String, Object> map = new HashMap<>();
        map.put("type", 1);//1表示来单提醒,2表示客户催单
        map.put("orderId", orders.getId());
        map.put("content","订单号:"+outTradeNo);
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    private void isAbleDelivery(String userAddress) {
        //构建店铺位置请求参数
        Map<String,String> Map=new HashMap<>();
        Map.put("address",shopAddress);
        Map.put("ak",ak);
        Map.put("output","json");
        //调用百度接口获取经纬度
        String ShopjsonString = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", Map);
        JSONObject jsonObject = JSON.parseObject(ShopjsonString);
        if(!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        //得到经度
        String lng = location.getString("lng");
        int index = lng.indexOf('.');
        lng=lng.substring(0,index)+lng.substring(index,index+7);
        //得到维度
        String lat = location.getString("lat");

        index = lat.indexOf('.');
        lat=lat.substring(0,index)+lat.substring(index,index+7);

        //得到起点经纬度
        String origin=lat+","+lng;

        log.info("店铺的位置:{}",origin);
        //构建用户位置请求参数
        Map<String,String> UMap=new HashMap<>();
        UMap.put("ak",ak);
        UMap.put("output","json");
        UMap.put("address",userAddress);
        log.info("address:{}",userAddress);
        //调用百度接口获取经纬度
        String UserjsonString = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", UMap);
        //将json字符串转为json对象
        JSONObject UjsonObject = JSON.parseObject(UserjsonString);
        //判断地址是否解析成功
        if(!UjsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("用户地址解析失败");
        }
        JSONObject UserLocation = UjsonObject.getJSONObject("result").getJSONObject("location");
        //得到经度
        String lngUser = UserLocation.getString("lng");
        index = lngUser.indexOf('.');
        lngUser=lngUser.substring(0,index)+lngUser.substring(index,index+7);
        //得到维度
        String latUser = UserLocation.getString("lat");
        log.info("用户维度:{}",latUser);
        index = latUser.indexOf('.');
        latUser=latUser.substring(0,index)+latUser.substring(index,index+7);
        //得到终点经纬度
        String end=latUser+","+lngUser;
        log.info("用户的位置:{}",end);
        //计算骑手配送距离
        Map<String,String>  directionliteMap=new HashMap<>();

        directionliteMap.put("origin",origin);
        directionliteMap.put("destination",end);
        directionliteMap.put("ak",ak);
        //设置已电动车为主要依据计算距离
        directionliteMap.put("riding_type","1");
        //directionliteMap.put("steps_info","0");
        //调用百度接口计算两地距离
        String jsonStr = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/riding", directionliteMap);
        JSONObject parseObject = JSON.parseObject(jsonStr);
        if(!parseObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }
        JSONArray routes= parseObject.getJSONObject("result").getJSONArray("routes");

        Integer distance = (Integer) ((JSONObject)routes.get(0)).get("distance");
//        JSONObject result = parseObject.getJSONObject("result");
//        JSONArray jsonArray = (JSONArray) result.get("routes");
//        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");
        log.info("配送距离:{}",distance);
        if(distance>5000){
            //配送距离超过5公里报出异常
            throw new OrderBusinessException("超出配送范围");
        }

    }

    @Override
    public PageResult pageList(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page =orderMapper.pageList(ordersPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public OrderStatisticsVO statistics() {
        //查询待接单的数量
        Integer toBeConfirmedCount=orderMapper.statisticsto(Orders.TO_BE_CONFIRMED);
        //查询待派送的数量
        Integer confirmedCount=orderMapper.statisticsto(Orders.CONFIRMED);
        //查询派送中的数量
        Integer deliveryInProgress=orderMapper.statisticsto(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmedCount);
        orderStatisticsVO.setConfirmed(confirmedCount);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        //Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //支付状态
//        Integer payStatus = ordersDB.getPayStatus();
//        if (payStatus == 1) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO, orders);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }

    @Override
    public void confirm(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(3);
        orderMapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        //支付状态
//        Integer payStatus = ordersDB.getPayStatus();
//        if (payStatus == 1) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersRejectionDTO, orders);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    //获取订单详细信息
    @Override
    public OrderVO getDetailById(Long id) {
        //OrderVO orderVO= orderMapper.getDetailById(id);
        OrderVO orderVO = new OrderVO();
        //获取订单信息
        Orders orderById = orderMapper.getById(id);
        //判断订单是否存在
        if(orderById==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        BeanUtils.copyProperties(orderById,orderVO);
        //List<OrderDetail> orderDetailList = orderVO.getOrderDetailList();
        //获取订单关联的菜品信息
        List<OrderDetail> orderDetailList=orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetailList);
        //将菜品信息拼接为字符串
        List<String> orderDishesList=orderDetailList.
                stream().
                map(o-> o.getName()+"*"+o.getNumber()+";").
                collect(Collectors.toList());
        String orderDishes = String.join("", orderDishesList);
        log.info("菜品信息字符串:{}",orderDishes);
        orderVO.setOrderDishes(orderDishes);
        return orderVO;
    }

    @Override
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    @Override
    public void cancelUser(Long id) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);
        if(ordersDB==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
//        if (payStatus == 1) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }
        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setId(id);
        orderMapper.update(orders);
    }

    /*
    * 再来一单
    * 将订单的数据重新放入购物车
    * */
    @Override
    @Transactional
    public void repetition(Long id) {
        Long userId = BaseContext.getCurrentId();
        //获取订单的详情
        List<OrderDetail> orderDetailList=orderDetailMapper.getByOrderId(id);
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(o -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(o, shoppingCart);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        //批量插入购物车数据
        shopCartMapper.addBatch(shoppingCartList);
    }

    @Override
    public void reminder(Long id) {
        Orders ordersDB = orderMapper.getById(id);
        if(ordersDB==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map<String,Object> map= new HashMap<>();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号:"+ordersDB.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    @Override
    public PageResult pageUser(int page, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(page, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        Page<Orders> orders = orderMapper.pageList(ordersPageQueryDTO);
        List<OrderVO> orderVOS=new ArrayList<>();
        if(orders!=null&&orders.getTotal()>0){
            List<Orders> result = orders.getResult();
            for (Orders orders1 : result) {
                OrderVO detailById = getDetailById(orders1.getId());
                if(detailById!=null){
                    orderVOS.add(detailById);
                }
            }
        }
       return new PageResult(orders.getTotal(),orderVOS);

    }

}
